package cc.avatar.model.inventory;

import java.util.Calendar;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import cc.avatar.model.Location;
import cc.avatar.model.Product;

/**
 * 统计某产品当前 库存量 和 极限库存量（允许用在缓存期内的产品）
 * <ul>库存变更日志，以下业务操作会新增此日志
 * <li>初始入库</li>
 * <li>生产入库 - cache days</li>
 * <li>销售出库</li>
 * <li>客户退货(非损坏)</li>
 * <li>损坏</li>
 * <li>改板(一出一入)</li>
 * </ul>
 */
@Entity
@Table(name="t_inventory_log") 
public class InventoryChange {
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	private Long id;
	
	@ManyToOne
	private Product product;
	
	@ManyToOne
	private Location location;
	
	//出库类型的数量为负值
	private int quantity;
	
	@Temporal(TemporalType.TIMESTAMP)
	@Column(updatable = false)
	private Date createdTime;
	
	private int usageDelayDays = 0;
	
	private String comments;
	@Enumerated(EnumType.STRING)
	private InventoryChangeType type;
	
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Product getProduct() {
		return product;
	}

	public void setProduct(Product product) {
		this.product = product;
	}


	public int getQuantity() {
		return quantity;
	}

	public void setQuantity(int quantity) {
		this.quantity = quantity;
	}

	public Date getCreatedTime() {
		return createdTime;
	}

	public void setCreatedTime(Date createdTime) {
		this.createdTime = createdTime;
	}

	public InventoryChangeType getType() {
		return type;
	}

	public void setType(InventoryChangeType type) {
		this.type = type;
	}
	
	public String getComments() {
		return comments;
	}

	public void setComments(String comments) {
		this.comments = comments;
	}
	
	public int getUsageDelayDays() {
		return usageDelayDays;
	}

	public void setUsageDelayDays(int usageDelayDays) {
		this.usageDelayDays = usageDelayDays;
	}

	public Location getLocation() {
		return location;
	}

	public void setLocation(Location location) {
		this.location = location;
	}

	public boolean isAvailable(){
		if (this.quantity < 0 || this.usageDelayDays == 0)
			return true;
		Calendar calender = Calendar.getInstance();
		calender.setTime(this.createdTime);
		calender.add(Calendar.DAY_OF_YEAR, this.usageDelayDays);
		
		Date now = new Date();
		return now.after(calender.getTime());
	}

}
